package com.bowlong.objpool;

import java.io.IOException;

import com.bowlong.net.ReSocket;

public class ReSocketPool extends AbstractQueueObjPool<ReSocket> {
	public static ReSocketPool POOL;

	public static final ReSocket borrowObject() throws Exception {
		if (!isInit)
			throw new Exception("need init host and port.");
		ReSocket r2 = POOL.borrow();
		return r2;
	}

	public ReSocketPool() {
	}

	public ReSocketPool(int num) {
		for (int i = 0; i < num; i++) {
			returnObj(createObj());
		}
	}

	static boolean isInit;
	static String HOST;
	static int PORT;

	public static final void init(String host, int port) {
		int max = 2;
		init(host, port, max);
	}

	public static final void init(String host, int port, int max) {
		HOST = host;
		PORT = port;
		POOL = new ReSocketPool(max);

		isInit = true;
	}

	public static final void returnObject(ReSocket obj) throws Exception {
		if (!isInit)
			throw new Exception("need init host and port.");

		POOL.returnObj(obj);
	}

	@Override
	public final ReSocket createObj() {
		try {
			ReSocket r2 = new ReSocket(HOST, PORT);
			r2.pool = this;
			return r2;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public final ReSocket resetObj(ReSocket obj) {
		return obj;
	}

	@Override
	public final ReSocket destoryObj(ReSocket obj) {
		obj.pool = null;
		obj.close();
		return obj;
	}

}
